﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.IO;
using System.Web;
using System.Dynamic;
using _180FrameWork.Common.Models;

namespace _180FrameWork.Common
{
    public class WebApiHelper : BaseWebClientHelper
    { 
        public WebApiHelper()
        {

        }

        private IDictionary<string, string> getHeader(object header)
        {
            if (header == null)
            {
                return null;
            }
            else
            {
                IDictionary<string, string> newHeader = new Dictionary<string, string>();
          
                foreach (var p in header.GetType().GetProperties())
                {
                    string name = p.Name;
                    string value = p.GetValue(header, null).ToStr();
                    if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                    {
                        newHeader.Add(name, value);
                    }
                }
              
                return newHeader;
            }
        }

        #region post
 
        /// <summary>
        /// 执行jsonpost请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string PostJson(string url, object data = null, object header = null)
        {
            HttpWebRequest req = GetWebRequest(url, "POST", getHeader(header));
            req.ContentType = "application/json;charset=utf-8";

            if (data != null)
            {
                byte[] postData = Encoding.UTF8.GetBytes( (data).ObjToJson());
                req.GetRequestStream().Write(postData, 0, postData.Length);
                req.GetRequestStream().Close();
            }
            else
                req.ContentLength = 0;

            HttpWebResponse rsp;
            try
            {
                rsp = (HttpWebResponse)req.GetResponse();
            }
            catch (WebException e)
            {
                rsp = (HttpWebResponse)e.Response;
            }
            Encoding encoding = Encoding.UTF8;
            return GetResponseAsString(rsp, encoding);
        }

        //public string PostXml(string url) { }

        //public string PostXml(string url, object data) { 

        //}
        #endregion

        #region get

        /// <summary>
        /// 执行get请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Get(string url, IDictionary<string, object> data = null, object header = null)
        {
            if (data != null && data.Count > 0)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(data);
                }
                else
                {
                    url = url + "?" + BuildQuery(data);
                }
            }

            HttpWebRequest req = GetWebRequest(url, "GET", getHeader(header));
            req.ContentType = "text/html;charset=utf-8";

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

            Encoding encoding = Encoding.UTF8;
            return GetResponseAsString(rsp, encoding);
            //string strResponse = GetResponseAsString(rsp, encoding);
            //return Newtonsoft.Json.JsonConvert.DeserializeObject(strResponse);
        }
        /// <summary>
        /// 执行get请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string Get(string url, object data = null, object header = null)
        {
            if (data != null)
            {
                if (url.Contains("?"))
                {
                    url = url + "&" + BuildQuery(data);
                }
                else
                {
                    url = url + "?" + BuildQuery(data);
                }
            }

            HttpWebRequest req = GetWebRequest(url, "GET", getHeader(header));
            req.ContentType = "text/html;charset=utf-8";

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

            Encoding encoding = Encoding.UTF8;
            return GetResponseAsString(rsp, encoding);
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fileName"></param>
        /// <param name="processCallback"></param>
        /// <returns></returns>
        public MSG Download(string url, string fileName, Action<string, long> processCallback = null)
        {
            var msg = new MSG();
            if (url.Trim() == "")
            {
                msg.I = "url不能为空";
            }
            else
            {
                HttpWebRequest req = GetWebRequest(url, "GET");
                req.ContentType = "text/html;charset=utf-8";
                HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();

                if (fileName.Trim() == "")
                {
                    msg.I = "文件名不能为空";
                }
                else
                {
                    if (!Directory.Exists(Path.GetDirectoryName(fileName)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(fileName));
                    }
                    //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
                    Encoding encoding = Encoding.UTF8;
                    System.IO.Stream stream = null;
                    BinaryReader reader = null;
                    using (FileStream outputStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                    {
                        try
                        {
                            // 以字符流的方式读取HTTP响应
                            stream = rsp.GetResponseStream();
                            long totalLength = rsp.ContentLength;
                            reader = new BinaryReader(stream, encoding);
                            byte[] buffer = new byte[1024];
                            int bytesRead;
                            do
                            {
                                bytesRead = stream.Read(buffer, 0, buffer.Length);
                                outputStream.Write(buffer, 0, bytesRead);
                                if (processCallback != null)
                                {
                                    processCallback.Invoke(url, outputStream.Length / totalLength);
                                }
                            }
                            while (bytesRead != 0);
                            outputStream.Position = 0;
                            msg.R = true;
                        }
                        catch (Exception ex)
                        {
                            msg.I = ex.Message;
                        }
                        finally
                        {
                            // 释放资源
                            if (reader != null) reader.Close();
                            if (stream != null) stream.Close();
                            if (rsp != null) rsp.Close();
                        }
                    }
                }
            }
            return msg;
        }
        /// <summary>
        /// 下载流
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public Stream DownloadStream(string url)
        {
            HttpWebRequest req = GetWebRequest(url, "GET");
            req.ContentType = "text/html;charset=utf-8";

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            //Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
            Encoding encoding = Encoding.UTF8;
            return GetResponseAsStream(rsp, encoding);
        }

        #endregion

    }
}
